package Spider;


import DBC.DatabaseConnection;
import Factory.DAOFactory;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

/**
 * @program: 爬虫
 * @description: 测试课程表保存
 * @author: 王代涛
 * @create: 2021-05-12 22:47
 **/
@SuppressWarnings("JavaDoc")
public class getCourse {
    public static boolean forCourse(String username, String password, Connection conn) throws NullPointerException{
        String indexUrl = "http://class.sise.com.cn:7001/sise/";
        String loginUrl = "http://class.sise.com.cn:7001/sise/login_check_login.jsp";
        String targetUrl = "http://class.sise.com.cn:7001/sise/module/student_schedular/student_schedular.jsp";
        CloseableHttpResponse response;
        int successCode = 200;
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpget对象,设置url访问地址
        HttpGet httpGet = new HttpGet(indexUrl);
        try {
            //使用httpclient发送请求,获取response
            response = httpClient.execute(httpGet);
            //解析响应
            if (response.getStatusLine().getStatusCode() == successCode){
                String content = EntityUtils.toString(response.getEntity(),"utf-8");
                //解析indexUrl
                Document doc = Jsoup.parse(content);
                Element element = doc.select("input[name]").first();
                //parmName,parmValue,parmRandom为登陆的post参数
                String parmName = element.attr("name");
                String parmValue = element.attr("value");

                if (parmName!=null&&parmValue!=null){
                    HttpPost httpPost = new HttpPost(loginUrl);

                    //封装登陆参数
                    ArrayList<NameValuePair> params = new ArrayList<>();
                    params.add(new BasicNameValuePair(parmName,parmValue));
                    params.add(new BasicNameValuePair("username",username));
                    params.add(new BasicNameValuePair("password",password));
                    //创建表单entity对象
                    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
                    httpPost.setEntity(formEntity);

                    response = httpClient.execute(httpPost);
                    if (response.getStatusLine().getStatusCode() == successCode){
                        httpGet = new HttpGet(targetUrl);
                        response = httpClient.execute(httpGet);
                        if (response.getStatusLine().getStatusCode() == successCode){
                            content = EntityUtils.toString(response.getEntity());
                            //解析targetUrl
                            //获取学生信息
                            Document name = Jsoup.parse(content);
                            Element studentInformation = name.select(".style16").first();
                            String studentInfo = studentInformation.text();
                            String studentName="NULL";
                            String id;
                            String year;
                            String major="NULL";
                            Scanner StudentScanner = new Scanner(studentInfo);
                            StudentScanner.useDelimiter("学号:|姓名:|年级:|专业:");
                            id = StudentScanner.next();
                            studentName = StudentScanner.next();
                            year = StudentScanner.next();
                            major = StudentScanner.next();

                            DAOFactory.UserInfoInstance(conn).saveUserInfo(
                                    studentName,
                                    id,
                                    year,
                                    major
                            );

                            //获取学生课程信息
                            Elements courses = name.getElementsByTag("td");
                            String courseindex="NULL",
                                    course="NULL",
                                    Class="NULL",
                                    teacher="NULL",
                                    classWeek="NULL",
                                    room="NULL",
                                    time="NULL",
                                    week="NULL",
                                    timetemp = "NULL";
                            int day = 1;
                            for (int i=0;i<64;i++) {
                                if(i%8==0) {
                                    day = 1;
                                    Scanner scanner = new Scanner(courses.eq(22 + i).text());
                                    scanner.useDelimiter("节\\s|-");
                                    scanner.next();
                                    scanner.next();
                                    time = scanner.next();//time
                                }else{
                                    courseindex = courses.eq(22 + i).text().isEmpty() ? "NULL" : courses.eq(22 + i).text();

                                    Scanner scanner = new Scanner(courseindex);
                                    scanner.useDelimiter("[\\p{Punct}]");
                                    if (courseindex!="NULL") {
                                        course = scanner.next();//course

                                        Scanner scanner2 = new Scanner(scanner.next());
                                        scanner2.useDelimiter("\\s");

                                        Class = scanner2.next();//class

                                        teacher = scanner2.next();//teacher

                                        StringBuffer temp = new StringBuffer();
                                        while (scanner2.hasNext()) {
                                            temp.append(scanner2.next() + " ");
                                        }
                                        classWeek = String.valueOf(temp);//week

                                        room = scanner.next();//room
                                        switch (day) {
                                            case 1:
                                                week = "星期一";
                                                break;
                                            case 2:
                                                week = "星期二";
                                                break;
                                            case 3:
                                                week = "星期三";
                                                break;
                                            case 4:
                                                week = "星期四";
                                                break;
                                            case 5:
                                                week = "星期五";
                                                break;
                                            case 6:
                                                week = "星期六";
                                                break;
                                            case 7:
                                                week = "星期日";
                                                break;
                                            default:
                                        }
                                        DAOFactory.SaveDataInstance(conn).saveCourse(
                                                course,
                                                Class,
                                                teacher,
                                                classWeek,
                                                room,
                                                time,
                                                id,
                                                studentName,
                                                year,
                                                major,
                                                week,
                                                "80"
                                        );
                                    }
                                    day++;
                                }
                                course="NULL";
                                Class="NULL";
                                teacher="NULL";
                                classWeek="NULL";
                                room="NULL";
                            }
                        }
                    }
                    return true;
                }
            }
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
